package com.zw.cloud.mybatis.plus.event;

import com.zw.cloud.mybatis.plus.entity.Fc;
import com.zw.cloud.mybatis.plus.entity.Tc;
import com.zw.cloud.mybatis.plus.service.api.IFcService;
import com.zw.cloud.mybatis.plus.service.api.ITcService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

@Slf4j
@Component
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    Environment environment;
    @Autowired
    private ITcService tcService;
    @Autowired
    private IFcService fcService;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        log.info("[ApplicationReadyEvent]......");
        String osName = environment.getProperty("os.name");
        if (StringUtils.isNotBlank(osName) && osName.startsWith("Windows")) {
            File file = new File("D:\\kafka_2.13-3.2.1");
            if (!file.exists()) {
                return;
            }
            handleTc();
            handleFc();

        }
    }

    private void handleTc() {
        for (int i = 1; i <= 5; i++) {
            List<Tc> tcList = tcService.queryTcListFromRemote(i);
            if (CollectionUtils.isEmpty(tcList)) {
                return;
            }
            for (Tc tc : tcList) {
                try {
                    tcService.save(tc);
                } catch (Exception e) {
                    log.error("[ApplicationReadyEventListener][handleTc] error is ",e);
                    return;
                }
            }
            //tcService.saveBatch(tcList, tcList.size());
        }
    }

    private void handleFc() {
        for (int i = 1; i <= 5; i++) {
            List<Fc> fcList = fcService.queryFcListFromRemote(i);
            if (CollectionUtils.isEmpty(fcList)) {
                return;
            }
            for (Fc fc : fcList) {
                try {
                    fcService.save(fc);
                } catch (Exception e) {
                    log.error("[ApplicationReadyEventListener][handleFc] error is ",e);
                    fcService.queryList(6);
                    return;
                }
            }
            fcService.queryList(6);
        }
    }

}

